package org.example.servicemanage.config;

import org.example.servicemanage.filter.JwtAuthenticationTokenFilter;
import org.example.servicemanage.security.MyUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private MyUserDetailsService userDetailsService;


    @Bean
    public AuthenticationManager authenticationManager(PasswordEncoder passwordEncoder) {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailsService);         //将编写的UserDetailsService注入进来
        provider.setPasswordEncoder(passwordEncoder);               //将使用的密码编译器加入进来
        ProviderManager manager = new ProviderManager(provider);    //将provider放置到AuthenticationManager 中
        return manager;
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf(csrf -> csrf.disable());
        httpSecurity.authorizeHttpRequests(it ->
                it.requestMatchers("/user/login", "/user/register",
                                "/doc.html", "/webjars/**", "/v3/api-docs/**",
                                "/swagger-resources/**", "/swagger-ui/**", "/swagger-ui.html",
                                "/knife4j/**", "/v3/api-docs.yaml", "/swagger-ui.html/**",
                                "/favicon.ico", "/error").permitAll()   //允许访问的接口
                        .anyRequest().authenticated()       //其余所有接口都需要认证
        );
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter, BasicAuthenticationFilter.class);

        return httpSecurity.build();
    }
}
